import { BLUE_STATE } from './blueState.js'
import { ConnectController } from './controller.js'

let bleConnectDeviceID = null

export const Blue = {
	/**
	 * 蓝牙连接状态：200-> 已连接；-1 ->未连接
	 */
	connectState: -1,

	/**
	 * 扫描蓝牙设备
	 * @param onlyBind 是否单独绑定操作，默认false
	 * @param module 设备模块，区分设备
	 */
	start() {
		uni.openBluetoothAdapter({
			success: ()=> {
				this.startBluetoothDevicesDiscovery()
			},
			fail: (res)=> {
				console.error('打开蓝牙适配器失败：', res)
				if (res.errCode === 10001) {
					if(res.state === 3) {
						ConnectController.connectStateListen(BLUE_STATE.NOBLUETOOTHPERMISSION)
					}else {
						ConnectController.connectStateListen(BLUE_STATE.UNAVAILABLE)
					}

				}
				// Android 系统特有，系统版本低于 4.3 不支持 BLE
				if(res.errCode === 10009) {
					ConnectController.connectStateListen(BLUE_STATE.VERSIONLOW)
				}
				if(res.errCode === 10008) {
					ConnectController.connectStateListen(BLUE_STATE.SYSTEMERROR)
				}
			},
			complete: ()=> {
				wx.offBluetoothAdapterStateChange()
				wx.onBluetoothAdapterStateChange((res)=> {
					if(this._discoveryStarted) return
					if (res.available) {
						this._discoveryStarted = res.discovering
						ConnectController.connectStateListen(BLUE_STATE.SCANING)
						this.startBluetoothDevicesDiscovery()
					}else {
						// 蓝牙模块未开启
						ConnectController.connectStateListen(BLUE_STATE.UNAVAILABLE)
					}
				})
			}
		})
	},
	/**
	 * 关闭蓝牙、初始化BLE状态
	 */
	closeBlue() {
		if(bleConnectDeviceID) {
			wx.closeBLEConnection({
				deviceId: bleConnectDeviceID,
			})
		}
		bleConnectDeviceID = null
		this.connectState = -1
		this._discoveryStarted = false
		wx.closeBluetoothAdapter()
		wx.offBluetoothAdapterStateChange()
		wx.offBLEConnectionStateChange()
		wx.stopBluetoothDevicesDiscovery()
	},
	/**
	 * 断开蓝牙
	*/
	closeBLEConnection() {
		wx.closeBLEConnection({
			deviceId: bleConnectDeviceID,
			success: ()=> {
				bleConnectDeviceID = null
				this.connectState = -1
				uni.showToast({
					icon: 'none',
					title: '蓝牙已断开连接'
				})
			}
		})
	},

	startBluetoothDevicesDiscovery() {
		if (this._discoveryStarted) {
			return
		}
		this._discoveryStarted = true
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			interval: 1000,
			success: ()=> {
				this.onBluetoothDeviceFound()
				console.log('扫描中.....')
			},
			fail: (res)=> {
				console.error('搜索外围设备失败--', res)
				const { locationAuthorized } = uni.getSystemInfoSync()
				if(res.errCode === -1 && (res.errno === 1509008 || res.errno === 1509009) || !locationAuthorized) {
					this.closeBlue()
					ConnectController.connectStateListen(BLUE_STATE.NOLOCATIONPERMISSION)
				}
			}
		})
	},

	onBluetoothDeviceFound() {
		ConnectController.connectStateListen(BLUE_STATE.SCANING)

		uni.onBluetoothDeviceFound((res)=> {
			
			res.devices.forEach(device=> {
				const deviceName = device.name || device.localName
				if (!deviceName) return
				if(deviceName.indexOf('SCZN')>-1){
					ConnectController.devicesListen(device)
				}
			})
		})
	},

	createBLEConnection(deviceId) {
		if (bleConnectDeviceID == null) {
			bleConnectDeviceID = deviceId
			uni.createBLEConnection({
				deviceId: deviceId,
				success: ()=> {
					this.connectState = 200

					ConnectController.connectStateListen({
						...BLUE_STATE.CONNECTSUCCESS,
						deviceId
					})
					this.onBLEConnectionStateChange()
					uni.showToast({
						icon: 'none',
						title: '设备已连接'
					})
				},
				fail: (e)=> {
					console.log(e)
					ConnectController.connectStateListen(BLUE_STATE.CONNECTFAILED)
				},
			})
		}
	},

	onBLEConnectionStateChange() {
		uni.onBLEConnectionStateChange(res=> {
			if (!res.connected) {
				ConnectController.connectStateListen(BLUE_STATE.DISCONNECT)
				this.connectState = -1
				this.closeBlue()
			}
		})
	},
}
